import Vue from 'vue';
import CarouselImgVue from './CarouselImg.vue';

const CarouselImgConstructor = Vue.extend(CarouselImgVue);
let instance;

const initInstance = () => {
  instance = new CarouselImgConstructor({
    el: document.createElement('div')
  });
};

const showNextMsg = (data) => {
  if (!instance) {
    initInstance();
  }
  if (typeof data == 'string') {
    instance.imgs = data;
    instance.isSingle = true;
  } else {
    instance.imgs = data.imgs;
    instance.index = data.index == 0 ? 1 : 0;
    instance.isSingle = false;

    Vue.nextTick(() => {
      if (instance.$refs.carousel) instance.$refs.carousel.setActiveItem(data.index);
    });
  }

  if (!instance.visible) {
    document.body.appendChild(instance.$el);

    Vue.nextTick(() => {
      instance.visible = true;
    });
  }
};

const CarouselImg = function (data) {
  if (typeof Promise !== 'undefined') {
    return new Promise((resolve, reject) => { // eslint-disable-line
      showNextMsg(data);
    });
  } else {
    showNextMsg(data);
  }
};

CarouselImg.show = (data) => {
  return CarouselImg(data);
};

export default CarouselImg;
export { CarouselImg };